package com.xxh.message.handler;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.xxh.common.utils.RedisUtil;
import com.xxh.dataaccess.entity.ChatMessage;
import com.xxh.dataaccess.service.ChatMessageService;
import com.xxh.message.config.Event;
import com.xxh.message.payload.BroadCastRequest;
import com.xxh.message.payload.ChatMessagePayLoad;
import com.xxh.message.payload.GropRequest;
import com.xxh.message.payload.JoinRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class MessageEventHandler {


    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private SocketIOServer server;

    @Resource
    ChatMessageService chatMessageService;

    /**
     * 添加connect事件，当客户端发起连接时调用
     *
     * @param client 客户端对象
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {
        if (client != null) {
            String token = client.getHandshakeData().getSingleUrlParam("token");
            // 模拟用户id 和token一致
            String userId = client.getHandshakeData().getSingleUrlParam("token");
            UUID sessionId = client.getSessionId();
            redisUtil.set(userId, String.valueOf(sessionId));
            log.info("连接成功,【token】= {},【sessionId】= {}", token, sessionId);
        } else {
            log.error("客户端为空");
        }
    }


    /**
     * 添加disconnect事件，客户端断开连接时调用，刷新客户端信息
     *
     * @param client 客户端对象
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        if (client != null) {
            String token = client.getHandshakeData().getSingleUrlParam("token");
            // 模拟用户id 和token一致
            String userId = client.getHandshakeData().getSingleUrlParam("token");
            UUID sessionId = client.getSessionId();
            //删除在线用户
            redisUtil.delete(userId);
            log.info("客户端断开连接,【token】= {},【sessionId】= {}", token, sessionId);
            client.disconnect();
        } else {
            log.error("客户端为空");
        }
    }

    @OnEvent(value = Event.JOIN)
    public void OnJoinChat(SocketIOClient client, AckRequest request, JoinRequest data) {
        System.out.println("发来消息：" + data);
        //将该用户加入群聊
        client.joinRoom(data.getGroupID());
        log.info("用户【" + data.getUserID() + "】" + "加入了群聊【" + data.getGroupID() + "】!!");
        //向群内所有用户广播该条消息
        server.getRoomOperations(data.getGroupID()).sendEvent(Event.JOIN, data);
    }

    @OnEvent(value = Event.GROUP)
    public void OnGroup(SocketIOClient client, AckRequest request, GropRequest data) {
        log.info("用户发送了群聊消息：" + data.getMessage());
        //判断客户端是否在群聊中
        Collection<SocketIOClient> clients = server.getRoomOperations(data.getGropid()).getClients();
        boolean inRoom = false;
        for (SocketIOClient cl : clients) {
            if (client.getSessionId().equals(cl.getSessionId())) {
                inRoom = true;
            }
        }
        if (inRoom) {
            //向群内所有用户广播该条消息
            server.getRoomOperations(data.getGropid()).sendEvent(Event.GROUP, data);
        } else {
            //向该用户提示请先加群
            data.setGropid("-1");
            data.setMessage("请加群聊后再发言");
            client.sendEvent(Event.GROUP, data);
        }
    }

    //私聊内容
    @OnEvent(value = Event.SINGLE)
    public void OnSingle(SocketIOClient client, AckRequest request, ChatMessagePayLoad data) {

        //该条消息存储消息历史数据库
        Integer from_id = data.getFromUser().getId();
        Integer to_id = data.getToContactId();
        String msg_content = data.getContent();
        Date now = new Date();
        ChatMessage message = new ChatMessage();
        message.setSendtime(now);
        message.setFromId(from_id);
        message.setToId(to_id);
        message.setMsgContent(msg_content);
        chatMessageService.save(message);


        //获取目标用户的会话ID
        String targetClientId = String.valueOf(data.getToContactId());
        UUID sessionId = UUID.fromString(redisUtil.get(targetClientId));
        data.setStatus("succeed");
        data.setId(String.valueOf(message.getId()));
        data.setToContactId(from_id);

        //发送给目标
        server.getClient(sessionId).sendEvent(Event.SINGLE, data);
    }

    /**
     * 广播消息
     *
     * @param message 消息内容
     */
    public void SendBroadCast(BroadCastRequest message) {
        Collection<SocketIOClient> clients = server.getAllClients();
        for (SocketIOClient c : clients) {
            c.sendEvent(Event.BRODACAST, message);
        }
    }


}
